package com.longge;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

public class FindShortestSubArray {

    public int findShortestSubArray(int[] nums) {

        Map<Integer, Integer[]> dMap = new HashMap<>();
        Map<Integer, Integer> cMap = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            Integer[] indexes = dMap.get(nums[i]);
            if (indexes == null) {
                dMap.put(nums[i], new Integer[]{i, i});
            } else {
                indexes[1] = i;
                dMap.put(nums[i], indexes);
            }
            cMap.put(nums[i], cMap.getOrDefault(nums[i], 0) + 1);
        }
        Integer maxCount = cMap.values().stream().sorted(Comparator.comparing(Integer::intValue).reversed()).findFirst().get();
        int min = Integer.MAX_VALUE;
        for (Map.Entry<Integer, Integer> entry : cMap.entrySet()) {
            if (entry.getValue().equals(maxCount)) {
                Integer[] indexes = dMap.get(entry.getKey());
                min = Math.min(min, indexes[1] - indexes[0] + 1);
            }
        }
        return min;


    }

}
